#!/bin/bash
set -eo pipefail

declare -r SCRIPT_DIR=$(cd $(dirname $0) >/dev/null 2>&1 && pwd)
source ${SCRIPT_DIR}/common.sh

declare -r tag=$1 container_name=$2 data=$3 config=$4 logs=$5

# Generate a self-signed TLS cert.
openssl req -batch -new \
    -newkey rsa:4096 \
    -x509 \
    -sha256 \
    -days 1 \
    -nodes \
    -subj "/C=US/ST=CA/L=./O=./OU=./CN=." \
    -out "${config}/tls.crt" \
    -keyout "${config}/tls.key"

declare -ra docker_run_influxd=(
    docker run -i -d
    --name=${container_name}
    -u $(id -u):influxdb
    -p 443:8086
    -v ${data}:/var/lib/influxdb2
    -v ${config}:/etc/influxdb2
    -e DOCKER_INFLUXDB_INIT_MODE=setup
    -e DOCKER_INFLUXDB_INIT_USERNAME=${TEST_USER}
    -e DOCKER_INFLUXDB_INIT_PASSWORD=${TEST_PASSWORD}
    -e DOCKER_INFLUXDB_INIT_ORG=${TEST_ORG}
    -e DOCKER_INFLUXDB_INIT_BUCKET=${TEST_BUCKET}
    -e INFLUXD_TLS_CERT=/etc/influxdb2/tls.crt \
    -e INFLUXD_TLS_KEY=/etc/influxdb2/tls.key \
    influxdb:${tag} influxd
)

log_msg Booting 2.x container in setup mode
if ! ${docker_run_influxd[@]} > /dev/null; then
    log_msg Error: Failed to launch container
    exit 1
fi
wait_container_ready_at_url "https://localhost/health"

# Check that the DB reports it's been set up.
log_msg Checking onboarding API post-start
declare onboarding_allowed=$(curl -sk https://localhost/api/v2/setup | jq .allowed)
if [[ ${onboarding_allowed} != 'false' ]]; then
    log_msg Error: Onboarding allowed post-start
    exit 1
fi

# Get the auth token generated by setup.
declare -r auth_token=$(extract_token ${container_name})

# Make sure we can use the generated auth token to find the resources we expect.
log_msg Checking org list post-setup
declare orgs=$(curl -sk -H "Authorization: Token ${auth_token}" https://localhost/api/v2/orgs | jq -r .orgs[].name)
if [[ ${orgs} != ${TEST_ORG} ]]; then
    log_msg Error: Bad org list post-setup
    echo ${orgs}
    exit 1
fi

log_msg Checking bucket list post-setup
declare buckets=$(curl -sk -H "Authorization: Token ${auth_token}" "https://localhost/api/v2/buckets?name=${TEST_BUCKET}" | jq -r .buckets[].name)
if [[ ${buckets} != ${TEST_BUCKET} ]]; then
    log_msg Error: Bad bucket list post-setup
    echo ${buckets}
    exit 1
fi
